#include "bsp_uart.h"
#include "text.h"
#include "usart.h"

Data_ProgressTypeDef Data_Pro;
CircularBuffer rx_buffer ={0};

extern uint8_t data[26];

#define BUFFER_SIZE 64  // 环形缓冲区长度
extern uint8_t rx_circular_buf[BUFFER_SIZE];  // 环形缓冲区
volatile uint16_t write_ptr = 0;    //写指针
volatile uint8_t write_len = 0;     //已写入长度
volatile uint8_t head_flag= 0;    //帧头
uint16_t read_ptr = 0;              //读指针 
#define FRAME_LEN 26

//uint8_t Bool_Rx(uint8_t* data) 
//{
//    if (data[0] != 0xAA) 
//	{
//        return 0;
//    }   
//    if (data[25] != 0xBC)		
//	{ 
//        return 0;
//    }
//    return 1;
//}

void Rx_Progress(uint8_t* data,gimbal_TypeDef* Gimbal,Data_ProgressTypeDef* Data_Pro,uint8_t point)
{
	for(int i=0;i<24;i++)
	{
		Data_Pro->byte[i]=data[(i+1+point)% BUFFER_SIZE];
	}
    
	Gimbal->X1=Data_Pro->buffer[0];
	Gimbal->Y1=Data_Pro->buffer[1];
	Gimbal->X2=Data_Pro->buffer[2];
	Gimbal->Y2=Data_Pro->buffer[3];
	Gimbal->X3=Data_Pro->buffer[4];
	Gimbal->Y3=Data_Pro->buffer[5];
	Gimbal->X4=Data_Pro->buffer[6];
	Gimbal->Y4=Data_Pro->buffer[7];
	Gimbal->Red_X=Data_Pro->buffer[8];
	Gimbal->Red_Y=Data_Pro->buffer[9];
	Gimbal->Green_X=Data_Pro->buffer[10];
	Gimbal->Green_Y=Data_Pro->buffer[11];
}

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) 
{
    if (huart->Instance == USART2) 
	{
        write_ptr = (write_ptr + 8) % BUFFER_SIZE;
        while ((read_ptr % BUFFER_SIZE) != (write_ptr % BUFFER_SIZE)) 
		{
            if (!head_flag && rx_circular_buf[read_ptr % BUFFER_SIZE] == 0xAA) 
			{
                head_flag = 1;
                write_len = 1;  
            }
            else if (head_flag && write_len < FRAME_LEN)
			{
                write_len++;
            }
            else if (write_len == FRAME_LEN) 
			{
                write_len = 0;
                head_flag = 0;  
				uint16_t tail_pos = (read_ptr - 1 + BUFFER_SIZE) % BUFFER_SIZE;
                if (rx_circular_buf[tail_pos] == 0xBC) 
				{
					Rx_Progress(rx_circular_buf, &Gimbal, &Data_Pro, (read_ptr - FRAME_LEN + 1 + BUFFER_SIZE) % BUFFER_SIZE);                
				}
            }
            read_ptr++;
        }
        read_ptr %= BUFFER_SIZE;
        write_ptr %= BUFFER_SIZE;
        HAL_UART_Receive_IT(&huart2, (uint8_t*)&rx_circular_buf[write_ptr], 8);
    }
}

void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart)
{
	if(huart->Instance == USART2)
	{
		HAL_UART_Receive_IT(&huart2, (uint8_t*)&rx_circular_buf[write_ptr], 8);
	}
}